const fs = require("fs");
const router = require("koa-router")();
//
function addMap(router,map){
    for (const key in map) {
        let path,
            getRegx = /GET\s+?/g,
            postRegx = /POST\s+?/g;
        if (map.hasOwnProperty(key)) {
            if(getRegx.test(key)){
                path = key.replace(getRegx,"");
                router.get(path,map[key]);
            }
            if(postRegx.test(key)){
                path = key.replace(postRegx,"");
                router.post(path,map[key]);
            }
        }
    }
}
//
function addControllers(dir="/controllers"){
    const files = fs.readdirSync(`${__dirname}${dir}`);
    const js_files = files.filter(f=>f.endsWith(".js"));
    const maps = js_files.map(jsName=>require(`${__dirname}${dir}/${jsName}`));
    //
    maps.forEach(map=>{
        addMap(router,map);
    })
    //
    return router.routes();
}
//
module.exports = {
    addControllers
}; 